package com.blacktea.webmagic.demo.strategy;

import cn.hutool.core.lang.Assert;
import com.blacktea.webmagic.demo.domain.BrowseDownload;
import com.blacktea.webmagic.demo.domain.Download;
import com.blacktea.webmagic.demo.domain.LocalDownload;
import com.blacktea.webmagic.demo.strategy.download.DownloadBrowseStrategy;
import com.blacktea.webmagic.demo.strategy.download.DownloadLocalStrategy;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;
import java.util.zip.ZipOutputStream;

/**
 * @description:
 * @author: black tea
 * @date: 2021/9/26 14:25
 */
public class DownloadContext {

    private DownloadStrategy downloadStrategy;

    private DownloadContext() {
    }

    public DownloadContext(DownloadStrategy downloadStrategy) {
        this.downloadStrategy = downloadStrategy;
    }

    public static Optional<DownloadContext> context(Download download) {
        if (download instanceof LocalDownload){
            return Optional.of(new DownloadContext(new DownloadLocalStrategy()));
        }else if (download instanceof BrowseDownload){
            return Optional.of(new DownloadContext(new DownloadBrowseStrategy()));
        }
        return Optional.empty();
    }

    public void executCheck(Download download){
        downloadStrategy.check(download);
    }

    public void executDownloadMd(Download download, String html){
        String pathOrName = "";
        HttpServletResponse response = null;
        if (download instanceof LocalDownload){
            pathOrName = ((LocalDownload) download).getPath()+download.getPage().getFileName();
        }else if (download instanceof BrowseDownload){
            pathOrName = download.getPage().getFileName();
            response = ((BrowseDownload) download).getResponse();
        }
        downloadStrategy.downloadMD(pathOrName,response,html);
    }

    public void executDownloadZip(Download download, Map<String, Map<String, String>> dataMap){
        String pathOrName = "";
        HttpServletResponse response = null;
        if (download instanceof LocalDownload){
            pathOrName = ((LocalDownload) download).getPath()+download.getPage().getFileName();
        }else if (download instanceof BrowseDownload){
            pathOrName = download.getPage().getFileName();
            response = ((BrowseDownload) download).getResponse();
        }else {
            Assert.state(false,"download类型为匹配到,当前类型:{}",download.getClass().getName());
        }
        downloadStrategy.downloadZip(pathOrName,response,dataMap);
    }

    public void executDownloadZip2(Download download, Map<String, Map<String, String>> dataMap){
        ZipOutputStream zos = download.getZipOutputStream();
        Optional.ofNullable(zos).ifPresent(z -> {
            downloadStrategy.downloadZip(z,dataMap);
        });
    }
}
